package com.example.administrator.energyida.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.energyida.R;
import com.example.administrator.energyida.activity.FormFactoryInfoActivity;
import com.example.administrator.energyida.activity.LinkManActivity;
import com.example.administrator.energyida.activity.PersonalAboutActivity;
import com.example.administrator.energyida.activity.PersonalHelpActivity;
import com.example.administrator.energyida.activity.PersonalMyinfoActivity;
import com.example.administrator.energyida.activity.TableActivity;
import com.example.administrator.energyida.beans.CompanyBean;
import com.example.administrator.energyida.util.OceanUtil;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.MODE_PRIVATE;

public class PersonalFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private ListView listViewUp;
    private ListView listViewDown;
    private SimpleAdapter simpleAdapterUp;
    private SimpleAdapter simpleAdapterDown;
    private List<Map<String, Object>> listDataUp;
    private List<Map<String, Object>> listDataDown;
    private ConstraintLayout lyPersonalInfo;
    private ImageView imageViewLogo;
    private TextView textViewCompany;
    private TextView textViewCity;
    private TextView textViewPhone;
    private Switch aSwitchNotify;

    private String email;
    private String response;
    private Handler handler;
    private List<CompanyBean.ContentBean> listCompanyBeans;
    private String companyName;
    private String city;
    private String companyPhone;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public PersonalFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PersonalFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static PersonalFragment newInstance(String param1, String param2) {
        PersonalFragment fragment = new PersonalFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View mView = inflater.inflate(R.layout.fragment_personal, container, false);

        // 设置状态栏的颜色
        StatusBarUtil.setColor(getActivity(), Color.parseColor("#10cafd"), 50);

        initViews(mView);
        initHandler();

        lyPersonalInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), PersonalMyinfoActivity.class);
                startActivity(intent);
            }
        });

        listDataUp = new ArrayList<>();
        listDataUp = getData("up");

        simpleAdapterUp = new SimpleAdapter(this.getActivity(),
                listDataUp,
                R.layout.item_listview_personal,
                new String[]{"img", "text", "next"},
                new int[]{
                        R.id.personal_listview_img,
                        R.id.personal_listview_text,
                        R.id.personal_listview_imageView_next
                });

        listViewUp.setAdapter(simpleAdapterUp);



        listDataDown = new ArrayList<>();
        listDataDown = getData("down");

        simpleAdapterDown = new SimpleAdapter(this.getActivity(),
                listDataDown,
                R.layout.item_listview_personal,
                new String[]{"img", "text", "next"},
                new int[]{
                        R.id.personal_listview_img,
                        R.id.personal_listview_text,
                        R.id.personal_listview_imageView_next
                });

        listViewDown.setAdapter(simpleAdapterDown);

        listViewUp.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), LinkManActivity.class);
                        startActivity(intent);
                        break;
                    case 1:
                        Intent intent1 = new Intent();
                        intent1.putExtra("from", "personal");
                        intent1.setClass(getActivity(), FormFactoryInfoActivity.class);
                        startActivity(intent1);
                        break;
                    default:
                        break;
                }
            }
        });

        listViewDown.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), PersonalHelpActivity.class);
                        startActivity(intent);
                        break;
                    case 1:
                        Intent intent1 = new Intent();
                        intent1.setClass(getActivity(), PersonalAboutActivity.class);
                        startActivity(intent1);
                        break;
                    default:
                        break;
                }
            }
        });

        aSwitchNotify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (aSwitchNotify.isChecked()) {
                    Toast.makeText(getActivity(), "通知开启", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "通知关闭", Toast.LENGTH_SHORT).show();
                }
            }
        });

        return mView;
    }


    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private List<Map<String, Object>> getData(String whichList) {

        switch(whichList) {
            case "up":
                HashMap<String, Object> map1 = new HashMap<>();
                map1.put("img", R.drawable.contacts);
                map1.put("text", "联系负责人");
                map1.put("next", R.drawable.next1);
                listDataUp.add(map1);

                HashMap<String, Object> map2 = new HashMap<>();
                map2.put("img", R.drawable.manage);
                map2.put("text", "管理工厂");
                map2.put("next", R.drawable.next1);
                listDataUp.add(map2);

                return listDataUp;
            case "down":
                HashMap<String, Object> map4 = new HashMap<>();
                map4.put("img", R.drawable.help);
                map4.put("text", "帮助");
                map4.put("next", R.drawable.next1);
                listDataDown.add(map4);

                HashMap<String, Object> map5 = new HashMap<>();
                map5.put("img", R.drawable.about);
                map5.put("text", "关于");
                map5.put("next", R.drawable.next1);
                listDataDown.add(map5);

                return listDataDown;
            default:
                return null;
        }
    }

    public void alpha(View v) {
        // 创建透明度动画，第一个参数是开始的透明度，第二个参数是要转换到的透明度
        AlphaAnimation alphaAni = new AlphaAnimation(0.2f, 1);

        //设置动画执行的时间，单位是毫秒
        alphaAni.setDuration(1000);

        // 设置动画重复次数
        // -1或者Animation.INFINITE表示无限重复，正数表示重复次数，0表示不重复只播放一次
        alphaAni.setRepeatCount(0);

        // 启动动画
        v.startAnimation(alphaAni);
    }

    private void initViews(View mView) {
        lyPersonalInfo = mView.findViewById(R.id.personal_constraintLayout_personalInfo);
        listViewUp = mView.findViewById(R.id.personal_listView_up);
        listViewDown = mView.findViewById(R.id.personal_listView_down);
        imageViewLogo = mView.findViewById(R.id.imageViewLogo);
        textViewCompany = mView.findViewById(R.id.personal_text_companyName);
        textViewCity = mView.findViewById(R.id.personal_text_city);
        textViewPhone = mView.findViewById(R.id.personal_text_phone);
        aSwitchNotify = mView.findViewById(R.id.personal_notify_switch);
        alpha(imageViewLogo);

//        getData();
    }

    @SuppressLint("HandlerLeak")
    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        if (response.contains("10007")) {
                            Log.i("坐标", "获得公司信息成功 ");
                            Gson gson = new Gson();
                            CompanyBean companyBean = gson.fromJson(response, CompanyBean.class);
                            listCompanyBeans = companyBean.getContent();

                            companyName = listCompanyBeans.get(0).getCompany();
                            city = listCompanyBeans.get(0).getCity();
                            companyPhone = listCompanyBeans.get(0).getPhone();

                            textViewCompany.setText(companyName);
                            textViewCity.setText(city);
                            textViewPhone.setText(companyPhone);
                        }
                        if (response.contains("-20007")) {
                            Toast.makeText(getActivity(), "公司信息获取失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        };
    }

    private void getData() {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("account",MODE_PRIVATE);
        email = sharedPreferences.getString("email", "");

        JSONObject getPoint = new JSONObject();
        try {
            getPoint.put("email", email);
            getPoint.put("mode", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new OceanUtil("getAccountAllInfo.php", getPoint, new OceanUtil.HttpRequestCallback() {
            @Override
            public void callback(String strResponse) {
                response = strResponse;
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
            }
        }).postInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }
}
